package com.gpnu.crm.service.impl;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gpnu.crm.domain.Permission;
import com.gpnu.crm.mapper.PermissionMapper;
import com.gpnu.crm.query.QueryObject;
import com.gpnu.crm.service.IPermissionService;

@Service
public class PermissionServiceImpl implements IPermissionService{
	  @Autowired
	  private PermissionMapper permissionMapper;
	  @Autowired
	  private ApplicationContext ctx;
	  
	  public PermissionServiceImpl() {}
	  
	  public void reload()
	  {
	    List<String> exps = permissionMapper.selectAllExpressions();
	    

	    Collection<Object> ctrls = ctx.getBeansWithAnnotation(Controller.class).values();
	    for (Object ctrl : ctrls)
	    {
	      if (org.springframework.aop.support.AopUtils.isCglibProxy(ctrl))
	      {
	        Method[] ms = ctrl.getClass().getSuperclass().getDeclaredMethods();
	        for (Method m : ms)
	        {
	          RequiresPermissions anno = (RequiresPermissions)m.getAnnotation(RequiresPermissions.class);
	          
	          if ((anno != null) && (!exps.contains(anno.value()[1])))
	          {
	            Permission p = new Permission();
	            p.setName(anno.value()[0]);
	            p.setExpression(anno.value()[1]);
	            permissionMapper.insert(p);
	          }
	        }
	      }
	    }
	  }
	  
	  public List<Permission> listNotByRoleId(long paramLong){
		  return permissionMapper.notSelectByRoleId(paramLong);
	  }
	  
	  public List<Permission> listByRoleId(long paramLong){
		  return permissionMapper.selectByRoleId(paramLong);
	  }
	  
	  public List<Permission> list() {
	    return permissionMapper.selectAll();
	  }
	  
	  public PageInfo<Permission> query(QueryObject qo) {
	    PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
	    List<Permission> list = permissionMapper.selectForList(qo);
	    return new PageInfo(list);
	  }

	
}
